define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yuncunchu/config/index' + location.search,
                    add_url: 'yuncunchu/config/add',
                    edit_url: 'yuncunchu/config/edit',
                    del_url: 'yuncunchu/config/del',
                    multi_url: 'yuncunchu/config/multi',
                    table: 'yuncunchu_config',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('配置名称')},
                        {field: 'type_text', title: __('存储类型')},
                        {field: 'status_text', title: __('状态')},
                        {field: 'is_default_text', title: __('是否默认')},
                        {field: 'createtime', title: __('创建时间'), formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('更新时间'), formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('操作'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                
                // 存储类型变化时显示对应的配置字段
                $('#c-type').on('change', function() {
                    var type = $(this).val();
                    if (type) {
                        Controller.api.showConfigFields(type);
                    } else {
                        $('#config-area').hide();
                    }
                });
                
                // 编辑页面初始化配置字段
                if ($('#c-type').val()) {
                    var configData = {};
                    var configDataElement = document.getElementById('config-data');
                    if (configDataElement && configDataElement.textContent) {
                        try {
                            configData = JSON.parse(configDataElement.textContent);
                        } catch (e) {
                            console.error('配置数据解析错误:', e);
                        }
                    }
                    Controller.api.showConfigFields($('#c-type').val(), true, configData);
                }
            },
            
            showConfigFields: function(type, isEdit, configData) {
                var configFields = '';
                
                switch(type) {
                    case 'local':
                        var path = isEdit && configData.path ? configData.path : '/uploads';
                        var url = isEdit && configData.url ? configData.url : '/uploads';
                        var directoryStructure = isEdit && configData.directory_structure ? configData.directory_structure : 'module/action/date';
                        configFields = `
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">存储路径:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][path]" type="text" value="${path}" placeholder="如：/uploads">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">访问URL:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][url]" type="text" value="${url}" placeholder="如：/uploads">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">目录结构:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][directory_structure]">
                                        <option value="module/action/date" ${directoryStructure === 'module/action/date' ? 'selected' : ''}>模块/动作/日期</option>
                                        <option value="module/action/date/hour" ${directoryStructure === 'module/action/date/hour' ? 'selected' : ''}>模块/动作/日期/小时</option>
                                        <option value="date/module" ${directoryStructure === 'date/module' ? 'selected' : ''}>日期/模块</option>
                                        <option value="module/date" ${directoryStructure === 'module/date' ? 'selected' : ''}>模块/日期</option>
                                        <option value="date" ${directoryStructure === 'date' ? 'selected' : ''}>仅日期</option>
                                    </select>
                                    <span class="help-block">选择文件在云存储中的目录结构</span>
                                </div>
                            </div>
                        `;
                        break;
                        
                    case 'aliyun_oss':
                        var accessKeyId = isEdit && configData.access_key_id ? configData.access_key_id : '';
                        var accessKeySecret = isEdit && configData.access_key_secret ? configData.access_key_secret : '';
                        var endpoint = isEdit && configData.endpoint ? configData.endpoint : '';
                        var bucket = isEdit && configData.bucket ? configData.bucket : '';
                        var domain = isEdit && configData.domain ? configData.domain : '';
                        var directoryStructure = isEdit && configData.directory_structure ? configData.directory_structure : 'module/action/date';
                        var localBackup = isEdit && configData.local_backup ? configData.local_backup : '0';
                        configFields = `
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">本地备份:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][local_backup]">
                                        <option value="0" ${localBackup === '0' ? 'selected' : ''}>不保留本地备份</option>
                                        <option value="1" ${localBackup === '1' ? 'selected' : ''}>同时保留本地备份</option>
                                    </select>
                                    <span class="help-block">开启后会在本地保留一份备份，目录结构与云端保持一致，便于灾备切换</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">AccessKey ID:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][access_key_id]" type="text" value="${accessKeyId}" placeholder="请输入AccessKey ID">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">AccessKey Secret:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][access_key_secret]" type="password" value="${accessKeySecret}" placeholder="请输入AccessKey Secret">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">Endpoint:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][endpoint]" type="text" value="${endpoint}" placeholder="如：oss-cn-hangzhou.aliyuncs.com">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">Bucket:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][bucket]" type="text" value="${bucket}" placeholder="请输入Bucket名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">域名:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][domain]" type="text" value="${domain}" placeholder="如：https://cdn.example.com">
                                </div>
                            </div>
                        `;
                        break;
                        
                    case 'tencent_cos':
                        var secretId = isEdit && configData.secret_id ? configData.secret_id : '';
                        var secretKey = isEdit && configData.secret_key ? configData.secret_key : '';
                        var region = isEdit && configData.region ? configData.region : '';
                        var bucket = isEdit && configData.bucket ? configData.bucket : '';
                        var domain = isEdit && configData.domain ? configData.domain : '';
                        var directoryStructure = isEdit && configData.directory_structure ? configData.directory_structure : 'module/action/date';
                        var localBackup = isEdit && configData.local_backup ? configData.local_backup : '0';
                        configFields = `
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">本地备份:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][local_backup]">
                                        <option value="0" ${localBackup === '0' ? 'selected' : ''}>不保留本地备份</option>
                                        <option value="1" ${localBackup === '1' ? 'selected' : ''}>同时保留本地备份</option>
                                    </select>
                                    <span class="help-block">开启后会在本地保留一份备份，目录结构与云端保持一致，便于灾备切换</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">SecretId:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][secret_id]" type="text" value="${secretId}" placeholder="请输入SecretId">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">SecretKey:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][secret_key]" type="password" value="${secretKey}" placeholder="请输入SecretKey">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">Region:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][region]" type="text" value="${region}" placeholder="如：ap-beijing-1">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">Bucket:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][bucket]" type="text" value="${bucket}" placeholder="请输入Bucket名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">域名:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][domain]" type="text" value="${domain}" placeholder="如：https://cdn.example.com">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">目录结构:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][directory_structure]">
                                        <option value="module/action/date" ${directoryStructure === 'module/action/date' ? 'selected' : ''}>模块/动作/日期</option>
                                        <option value="module/action/date/hour" ${directoryStructure === 'module/action/date/hour' ? 'selected' : ''}>模块/动作/日期/小时</option>
                                        <option value="date/module" ${directoryStructure === 'date/module' ? 'selected' : ''}>日期/模块</option>
                                        <option value="module/date" ${directoryStructure === 'module/date' ? 'selected' : ''}>模块/日期</option>
                                        <option value="date" ${directoryStructure === 'date' ? 'selected' : ''}>仅日期</option>
                                    </select>
                                    <span class="help-block">选择文件在云存储中的目录结构</span>
                                </div>
                            </div>
                        `;
                        break;
                        
                    case 'qiniu':
                        var accessKey = isEdit && configData.access_key ? configData.access_key : '';
                        var secretKey = isEdit && configData.secret_key ? configData.secret_key : '';
                        var bucket = isEdit && configData.bucket ? configData.bucket : '';
                        var domain = isEdit && configData.domain ? configData.domain : '';
                        var zone = isEdit && configData.zone ? configData.zone : 'auto';
                        var directoryStructure = isEdit && configData.directory_structure ? configData.directory_structure : 'module/action/date';
                        var localBackup = isEdit && configData.local_backup ? configData.local_backup : '0';
                        configFields = `
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">本地备份:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][local_backup]">
                                        <option value="0" ${localBackup === '0' ? 'selected' : ''}>不保留本地备份</option>
                                        <option value="1" ${localBackup === '1' ? 'selected' : ''}>同时保留本地备份</option>
                                    </select>
                                    <span class="help-block">开启后会在本地保留一份备份，目录结构与云端保持一致，便于灾备切换</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">AccessKey:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][access_key]" type="text" value="${accessKey}" placeholder="请输入AccessKey">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">SecretKey:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][secret_key]" type="password" value="${secretKey}" placeholder="请输入SecretKey">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">Bucket:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][bucket]" type="text" value="${bucket}" placeholder="请输入Bucket名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">域名:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <input class="form-control" name="row[config][domain]" type="text" value="${domain}" placeholder="如：https://cdn.example.com">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">存储区域:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][zone]">
                                        <option value="auto" ${zone === 'auto' ? 'selected' : ''}>自动检测</option>
                                        <option value="z0" ${zone === 'z0' ? 'selected' : ''}>华东</option>
                                        <option value="z1" ${zone === 'z1' ? 'selected' : ''}>华北</option>
                                        <option value="z2" ${zone === 'z2' ? 'selected' : ''}>华南</option>
                                        <option value="na0" ${zone === 'na0' ? 'selected' : ''}>北美</option>
                                        <option value="as0" ${zone === 'as0' ? 'selected' : ''}>东南亚</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-xs-12 col-sm-2">目录结构:</label>
                                <div class="col-xs-12 col-sm-8">
                                    <select class="form-control" name="row[config][directory_structure]">
                                        <option value="module/action/date" ${directoryStructure === 'module/action/date' ? 'selected' : ''}>模块/动作/日期</option>
                                        <option value="module/action/date/hour" ${directoryStructure === 'module/action/date/hour' ? 'selected' : ''}>模块/动作/日期/小时</option>
                                        <option value="date/module" ${directoryStructure === 'date/module' ? 'selected' : ''}>日期/模块</option>
                                        <option value="module/date" ${directoryStructure === 'module/date' ? 'selected' : ''}>模块/日期</option>
                                        <option value="date" ${directoryStructure === 'date' ? 'selected' : ''}>仅日期</option>
                                    </select>
                                    <span class="help-block">选择文件在云存储中的目录结构</span>
                                </div>
                            </div>
                        `;
                        break;
                }
                
                $('#config-fields').html(configFields);
                $('#config-area').show();
            }
        }
    };
    return Controller;
});
